<template>
  <div class="event-container">
    <!-- 头部导航 -->
    <el-header class="header">
      <div class="header-content">
        <h1>活动中心</h1>
        <div class="actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索活动..."
            clearable
            style="width: 300px; margin-left: 20px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </el-header>

    <!-- 活动列表 -->
    <el-main class="main-content">
      <div class="sort-controls">
        <el-radio-group v-model="sortType" @change="loadEvents">
          <el-radio-button label="time">最新活动</el-radio-button>
          <el-radio-button label="likes">最受欢迎</el-radio-button>
        </el-radio-group>
      </div>

      <el-skeleton :rows="6" animated :loading="loading">
        <template #default>
          <transition-group name="list" tag="div">
            <el-card 
              v-for="event in sortedEvents"
              :key="event.event_id"
              class="event-card"
              :class="{ 'is-top': event.is_top }"
            >
              <template #header>
                <div class="card-header">
                  <div class="title-container">
                    <el-tag v-if="event.is_top" type="danger" effect="dark">置顶</el-tag>
                    <h3>{{ event.title }}</h3>
                  </div>
                  <div class="header-actions">
                    <el-button 
                      v-if="isAdmin"
                      :content="isAdmin? '删除活动' : '禁止点击'"
                      type="danger" 
                      circle
                      @click="handleDelete(event.event_id)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                    <el-tooltip 
                      v-if="isAdmin"
                      :content="event.is_top ? '取消置顶' : '置顶'"
                      placement="top"
                    >
                      <el-button 
                        :type="event.is_top ? 'warning' : 'success'" 
                        circle
                        @click="toggleTop(event)"
                      >
                        <el-icon><Top /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </div>
              </template>

              <div class="event-content">
                <p class="description">{{ event.description }}</p>
                <div class="meta-info">
                  <div class="info-item">
                    <el-icon><User /></el-icon>
                    <span>发起人：用户{{ event.user_id }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ event.location }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ formatDate(event.event_date) }}</span>
                  </div>
                </div>
              </div>
              
              <div class="card-footer">
                <el-button 
                  :type="event.liked ? 'danger' : 'primary'" 
                >
                  <el-icon><Star /></el-icon>
                  {{ event.likes }} 点赞
                </el-button>
              </div>
            </el-card>
          </transition-group>
        </template>
      </el-skeleton>
    </el-main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Delete,
  Search,
  Top,
  User,
  Location,
  Clock
} from '@element-plus/icons-vue'
import axios from 'axios'

// 模拟当前管理员状态
const isAdmin = ref(true)

// 状态管理
const loading = ref(true)
const sortType = ref('time')
const searchKeyword = ref('')
const events = ref([])

// 计算属性
const sortedEvents = computed(() => {
  return [...events.value].sort((a, b) => {
    if (a.is_top !== b.is_top) return b.is_top - a.is_top
    if (sortType.value === 'likes') return b.likes - a.likes
    return new Date(b.event_date) - new Date(a.event_date)
  })
})

// 方法
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

// 加载活动列表
const loadEvents = async () => {
  try {
    loading.value = true
    const response = await axios.get(`/events?sort=${sortType.value}`)
    events.value = response.data
  } catch (error) {
    ElMessage.error('加载活动失败')
  } finally {
    loading.value = false
  }
}

// 搜索活动
const handleSearch = async () => {
  try {
    const response = await axios.get(`/events/search?sort=time`, {
      params: { keyword: searchKeyword.value }
    })
    events.value = response.data
  } catch (error) {
    ElMessage.error('搜索失败')
  }
}

// 删除活动
const handleDelete = async (eventId) => {
  try {
    await ElMessageBox.confirm('确定要删除该活动吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await axios.delete(`/events/${eventId}`)
    events.value = events.value.filter(e => e.event_id !== eventId)
    ElMessage.success('删除成功')
  } catch {
    // 取消删除
  }
}

// 置顶/取消置顶活动
const toggleTop = async (event) => {
  try {
    const url = event.is_top ? `/events/${event.event_id}/untop` : `/events/${event.event_id}/top`
    await axios.put(url)
    event.is_top = !event.is_top
    ElMessage.success(event.is_top ? '已置顶' : '已取消置顶')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  loadEvents()
})
</script>

<style scoped>
.event-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.header {
  background: linear-gradient(135deg, #409eff, #79bbff);
  color: white;
  margin-top: 30px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.sort-controls {
  margin-bottom: 20px;
}

.event-card {
  border-left: 4px solid #b4dfff;
  background: #effaff;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.event-card.is-top {
  border-left: 4px solid #e6a23c;
  background: #fff9ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.event-content {
  padding: 10px 0;
}

.meta-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
  color: #666;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.card-footer {
  margin-top: 15px;
  text-align: right;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 移动端优化 */
@media (max-width: 480px) {
  /* 容器调整 */
  .event-container {
    padding: 10px;
  }

  /* 标题和头部样式调整 */
  .header {
    margin-bottom: 20px;
    text-align: center;  /* 让活动中心标题居中 */
    display: flex;
    justify-content: center; /* 居中 */
    align-items: center; /* 垂直居中 */
    height: 40px; /* 适当的高度 */
  }

  .header-content h1 {
    font-size: 1.5rem;
    margin: 0;
  }

  /* 使用Flexbox让标题、按钮、输入框排列 */
  .header-content {
    display: flex;
    flex-direction: column; /* 垂直堆叠 */
    align-items: center;  /* 居中对齐 */
    gap: 15px; /* 设置元素之间的间距 */
  }

  /* 选项卡下移 */
  .sort-controls {
    display: flex;
    flex-direction: column; /* 垂直堆叠 */
    align-items: center;  /* 居中对齐 */
    width: 100%;
    margin-top: 45px;  /* 强制下移选项卡 */
  }

  /* 搜索框样式 */
  .el-input {
    width: 100%;  /* 让搜索框占满父容器 */
    font-size: 14px;  /* 调整字体大小 */
    margin-bottom: 20px; /* 增加底部间距 */
  }

  /* 发布新活动按钮 */
  .el-button {
    width: 100%;  /* 让按钮占满父容器 */
    font-size: 14px;  /* 调整字体大小 */
    margin-bottom: 10px; /* 增加底部间距 */
  }

  /* 活动中心文字和按钮之间的间距调整 */
  .header-content > .el-button, 
  .header-content > .el-input {
    margin-bottom: 10px;  /* 每个元素底部增加间距，避免重叠 */
  }

  /* 调整卡片的间距 */
  .event-card {
    margin-bottom: 15px;
    padding: 10px;
    margin-top: 10px; /* 下移帖子卡片 */
  }

  /* 卡片内的信息内容 */
  .meta-info {
    display: block;  /* 让meta信息垂直排列 */
    margin-top: 10px;
  }

  .info-item {
    margin-bottom: 10px;  /* 增加信息项之间的间距 */
  }

  /* 按钮的文本大小和宽度 */
  .el-button {
    font-size: 14px;
    width: 100%;  /* 让按钮在手机端宽度适应屏幕 */
  }
}

</style>